package com.example.amap.baidu.search

import android.content.Context
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener
import com.baidu.mapapi.search.sug.SuggestionResult
import com.baidu.mapapi.search.sug.SuggestionSearch
import com.baidu.mapapi.search.sug.SuggestionSearchOption
import com.example.amap.lib.base.utils.LogUtil
import com.example.amap.search.bean.SearchSuggestInfo
import com.example.amap.search.observer.ISearchObserver
import com.example.amap.service.ISearchService

@Route(path = "/search/baidu/SearchServiceImpl")
class SearchServiceImpl : ISearchService, OnGetSuggestionResultListener {
    companion object {
        private const val TAG = "SearchServiceImpl"
    }

    private val observers = mutableSetOf<ISearchObserver>()

    private val suggestionSearch: SuggestionSearch by lazy { SuggestionSearch.newInstance() }

    override fun init(context: Context?) {
        suggestionSearch.setOnGetSuggestionResultListener(this)
    }

    override fun executeSearchSuggestion(keyWord: String, city: String) {
        val result = suggestionSearch.requestSuggestion(
            SuggestionSearchOption().keyword(keyWord).city(city)
        )
        LogUtil.d(TAG, "executeSearchSuggestion keyWord: $keyWord, city: $city, result: $result")
    }

    override fun onGetSuggestionResult(result: SuggestionResult?) {
        LogUtil.i(TAG, "result: ${result?.allSuggestions}")
        observers.forEach {
            it.onSearchSuggest(convertSuggestionResult(result?.allSuggestions))
        }
    }

    override fun addSearchObserver(observer: ISearchObserver) {
        LogUtil.d(TAG, "addSearchObserver observer: $observer")
        observers.add(observer)
    }

    override fun removeSearchObserver(observer: ISearchObserver) {
        LogUtil.d(TAG, "removeSearchObserver observer: $observer")
        observers.remove(observer)
    }

    private fun convertSuggestionResult(result: List<SuggestionResult.SuggestionInfo>?) =
        result?.map { SearchSuggestInfo(it.key, it.address) }
}